package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.FightProcessXmlResponse
import com.promise.jokerdream.utils.UrlFixer
import org.jsoup.Jsoup

class FightProcessXmlParser: BaseXmlParser<FightProcessXmlResponse>() {
    
    fun parseFightProcessXml(xmlString: String): XmlParseResult<FightProcessXmlResponse> {
        return parseXml(xmlString)
    }
    
    override fun doParse(xmlString: String): FightProcessXmlResponse {
        val doc = Jsoup.parse(xmlString)
        val divElement = doc.selectFirst("div#id") ?: return FightProcessXmlResponse(
            actionResult = "",
            xmlContent = xmlString
        )
        
        val divHtml = divElement.html()
        val divText = divElement.text()
        
        val roundStart = Regex("回合\\d+：").find(divHtml)?.range?.start
        val footerStart = Regex("战斗结束：|<a[^>]*>强化</a>").find(divHtml)?.range?.start ?: divHtml.length

        val header = if (roundStart != null) {
            divHtml.substring(0, roundStart)
        } else {
            divHtml.substring(0, footerStart)
        }
        
        val rounds = if (roundStart != null && footerStart > roundStart) {
            divHtml.substring(roundStart, footerStart)
        } else {
            ""
        }

        val footer = divHtml.substring(footerStart)
        
        val pageRegex = Regex("第(\\d+)/(\\d+)页")
        val pageMatch = pageRegex.find(divText)
        val currentPage = pageMatch?.groupValues?.get(1)?.toIntOrNull() ?: 1
        val totalPages = pageMatch?.groupValues?.get(2)?.toIntOrNull() ?: 1
        
        val nextPageLinkRegex = Regex("<a[^>]*href=\"([^\"]*)\"[^>]*>下一页</a>")
        val nextPageMatch = nextPageLinkRegex.find(divHtml)
        val nextPageLink = nextPageMatch?.groupValues?.get(1)?.let { UrlFixer.fixUrl(it) } ?: ""
        
        return FightProcessXmlResponse(
            actionResult = "",
            xmlContent = xmlString,
            header = header,
            rounds = rounds,
            footer = footer,
            currentPage = currentPage,
            totalPages = totalPages,
            nextPageLink = nextPageLink
        )
    }
}
